package com.neuronbit.businessflow.plugin.task;

import org.apache.commons.io.FileUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.component.ComponentIdentifier;
import org.gradle.api.artifacts.result.*;
import org.gradle.api.tasks.TaskAction;
import org.gradle.jvm.JvmLibrary;
import org.gradle.language.base.artifact.SourcesArtifact;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * The type Copy dependency task.
 *
 * @author spearwang
 */
public class CopyDependencyTask extends DefaultTask {

    /**
     * Sync api info.
     *
     * @throws IOException the io exception
     */
    @TaskAction
    public void execute() throws IOException {
        //copy source jar to download
        final List<ComponentIdentifier> collected = getProject().getConfigurations().getByName("runtimeClasspath")
                .getIncoming()
                .getResolutionResult()
                .getAllDependencies()
                .stream()
                .filter(dr -> dr instanceof ResolvedDependencyResult)
                .map(dr -> ((ResolvedDependencyResult) dr).getSelected().getId())
                .collect(Collectors.toList());
        final ArtifactResolutionResult result = getProject()
                .getDependencies()
                .createArtifactResolutionQuery()
                .forComponents(collected)
                .withArtifacts(JvmLibrary.class, SourcesArtifact.class)
                .execute();
        final File download = getProject().getBuildDir().toPath().resolve("dependency").toFile();
        if (download.exists()) {
            FileUtils.deleteQuietly(download);
        }

        download.mkdirs();
        for (ComponentArtifactsResult comp : result.getResolvedComponents()) {
            final Set<ArtifactResult> artifacts = comp.getArtifacts(SourcesArtifact.class);
            getProject().getLogger().info("found {} sources jar for {}", artifacts.size(), comp.getId());
            for (ArtifactResult artifact : artifacts) {
                if (artifact instanceof ResolvedArtifactResult) {
                    final File file = ((ResolvedArtifactResult) artifact).getFile();
                    if (file.exists() && !download.toPath().resolve(file.getName()).toFile().exists()) {
                        FileUtils.copyFileToDirectory(file, download);
                    }
                }
            }
        }
        //copy jar files into download
        for (File file : getProject().getConfigurations().getByName("runtimeClasspath").getFiles()) {
            if (file.exists() && !download.toPath().resolve(file.getName()).toFile().exists()) {
                FileUtils.copyFileToDirectory(file, download);
            }
        }
        //for library like lombok which involved only in the compile time
        for (File file : getProject().getConfigurations().getByName("compileClasspath").getFiles()) {
            if (file.exists() && !download.toPath().resolve(file.getName()).toFile().exists()) {
                FileUtils.copyFileToDirectory(file, download);
            }
        }
    }
}
